package com.yogurt.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yogurt.servicebase.handler.MyException;
import com.yogurt.ucenter.entity.Member;
import com.yogurt.ucenter.mapper.MemberMapper;
import com.yogurt.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yogurt.ucenter.vo.LoginVo;
import com.yogurt.ucenter.vo.RegisterVo;
import com.yogurt.utils.JwtUtils;
import com.yogurt.utils.MD5;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author yogurt
 * @since 2020-12-20
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    //用户登录
    @Override
    public String login(LoginVo vo) {
        String mobile = vo.getMobile();
        String password = vo.getPassword();
        //获取用户输入的手机号和密码,判断是否为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new MyException(20001,"手机号和密码不能为空");
        }
        //根据手机号查询用户
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Member member = baseMapper.selectOne(wrapper);
        //没有找到对应用户
        if (member == null){
            throw new MyException(20001,"用户名或密码有误,请重新输入");
        }
        //用户存在,判断输入的密码是否正确
        if (!MD5.encrypt(password).equals(member.getPassword())){
            throw new MyException(20001,"用户名或密码有误,请重新输入");
        }
        //判断是否是禁用状态
        if (member.getIsDisabled()){
            throw new MyException(20001,"该账户被禁用");
        }
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return token;
    }

    //用户注册
    @Override
    public void register(RegisterVo vo) {
        String mobile = vo.getMobile();
        String nickname = vo.getNickname();
        String password = vo.getPassword();
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password)){
            throw new MyException(20001,"请填写完整");
        }
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0){
            throw new MyException(20001,"该账号已被注册");
        }
        Member member = new Member();
        member.setMobile(mobile);
        member.setPassword(MD5.encrypt(password));
        member.setNickname(nickname);
        member.setAvatar("https://guli-eduproject.oss-cn-beijing.aliyuncs.com/xiaohuihui.jpg");
        //member.setIsDisabled(false);
        baseMapper.insert(member);
    }

    @Override
    public int countRegister(String date) {
        return baseMapper.countRegister(date);
    }
}
